// ClickedPoint.js
// Vertex shader 顶点着色器
var VSHADER_SOURCE = 
  "attribute vec4 a_Position;\n" + 
  "attribute float a_PointSize;\n" + 
  "void main() {\n" + 
  " gl_Position = a_Position;\n" + 
  " gl_PointSize = a_PointSize;\n" + 
  "}\n";

// Fragment shader 片段着色器
var FSHADER_SOURCE = 
  "void main() {\n" + 
  " gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n" + 
  "}\n";

function main() {
  var canvas = document.getElementById("webgl");

  var gl = getWebGLContext(canvas);
  if (!gl) {
    console.log("Failed to get the rendering context for WebGL");
    return;
  }

  if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
    console.log("Fialed to initialize shaders.");
    return;
  }

  // 获取变量a_Position的存储位置
  var a_Position = gl.getAttribLocation(gl.program, "a_Position");
  if (a_Position < 0) {
    console.log("Failed to get the storage location of a_Position");
    return;
  }

  var a_PointSize = gl.getAttribLocation(gl.program, "a_PointSize");
  if (a_PointSize < 0) {
    console.log("Failed to get the storage location of a_PointSize");
    return;
  }
  gl.vertexAttrib1f(a_PointSize, 5.0);

  // 注册canvas的鼠标点击事件响应函数
  canvas.onmousedown = function(event) {
    click(event, gl, canvas, a_Position);
  }

  gl.clearColor(0.0, 0.0, 0.0, 1.0);

  gl.clear(gl.COLOR_BUFFER_BIT);
}

var g_points = [];
function click(event, gl, canvas, a_Position) {
  var x = event.clientX;
  var y = event.clientY;
  // (rect.left, rect.top)是canvas的原点在浏览器中的坐标
  var rect = event.target.getBoundingClientRect();
  x = ((x - rect.left) - canvas.height/2)/(canvas.height/2);
  y = ((canvas.width/2 - (y - rect.top)))/(canvas.width/2);
  g_points.push(x);
  g_points.push(y);

  // 绘制点之后 颜色缓冲器会被WebGL重置为默认颜色(0.0, 0.0, 0.0, 0.0)
  gl.clear(gl.COLOR_BUFFER_BIT);

  var len = g_points.length;
  for (var i = 0; i < len; i+=2) {
    gl.vertexAttrib3f(a_Position, g_points[i], g_points[i+1], 0.0);

    gl.drawArrays(gl.POINTS, 0, 1);
  }
}